<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/10/9
 * Time: 9:04
 */

namespace Admin\Frontend\Controllers;


use Admin\Models\school\XhschoolInfo;
use Admin\Models\track\XhtrackTch;
use Admin\Models\user\XhsysUser;
use Helpers\Assets;
use Helpers\Hrm;
use Helpers\Main;
use Helpers\Template;
use Helpers\XhException;
use Modules\Msg;
use Modules\Power;
use Modules\School;

class TchLogController extends ControllerBase
{

    public static $enums = [
        'iTrackType' => [1 => '应用', 2 => '教辅'],
        'iState'     => [1 => '待审核', 2 => '审核通过',3 => '未通过']
    ];

    /**
     * 教师日志
     *
     * @return \Phalcon\Mvc\View
     *
     * create by dale  20181009
     */
    public function indexAction()
    {
//        $this->view->setTemplateBefore('listlist');
        $this->view->pick('tch_log/index');
        Assets::easyUI();
        Assets::importJs('js/tch_log/index.js');

        Template::exists('XHSchool_Info', 'list') && Template::exists('Tch_Track', 'list')
        or die(Main::showMessageModal('配置文件不存在，请先创建！', 109106010));
        $schSearchArr = $tchSearchArr = $tchListButtonArr = [];

        $schSearchArr[] = ['type'=>'text', 'id'=>'SchoolList_Search','style'=>'width:100px;','label'=>'搜索: '];
        $schSearchArr[] = ['type'=>'button', 'id'=>'bt_SchoolList_Search', 'text'=>'确定',
            'icon'=>'fa-search', 'style'=>'margin-left:5px'];
        $tchSearchArr[] = array('type' => 'select', 'id' => 'select_state',
            'data' => [0 => '全部'] + self::$enums['iState'], 'default' => 0 );
        $tchSearchArr[] = array('type' => 'text', 'id' => 'List_Search_StartTime', 'label' => ' 时间：',
            'class'=>'easyui-datebox','style'=>'width:100px !important ;','value' => date('Y-m').'-01');
        $tchSearchArr[] = array('type' => 'text', 'id' => 'List_Search_EndTime', 'label' => ' ~',
            'class'=>'easyui-datebox','style'=>'width:100px !important ;', 'value' => date('Y-m-d'));
        $tchSearchArr[] = ['type'=>'text', 'id'=>'TeacherList_Search', 'label'=>' ','style'=>'width:100px;'];
        $tchSearchArr[] = ['type'=>'button', 'id'=>'bt_TeacherList_Search', 'text'=>'确定',
            'icon'=>'fa-search', 'style'=>'margin-left:10px'];
        if (Power::exist('School_Teacher_Track_Edit')) {
            $tchListButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_pass', 'text' => '审核通过',
                'icon' => 'fa-check');
            $tchListButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_unpass', 'text' => '审核不通过',
                'icon' => 'fa-times');
        }
        return $this->view->setVars([
            'SchoolList'    => Template::createList('schoolList', 'XHSchool_Info', [
                'searchToolbar' => Template::createSearchToolBar($schSearchArr),
                'checkbox'      => false,
                'field'         => ['iSchoolId', 'sSchoolName'],
                'tableAttr'     => ['singleSelect' => 'true']
            ]),
            'TeacherList'   => Template::createList('logList', 'Tch_Track', [
                'searchToolbar' => Template::createSearchToolBar($tchSearchArr, true),
                'buttonToolbar' => Template::createButtonToolBar($tchListButtonArr),
            ])
        ]);
    }

    /**
     * 获取学校
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20181009
     */
    public function getSchoolAction()
    {
        try {
            $key = $this->request->getPost('key', 'string');
            $builder = $this->modelsManager->createBuilder()
                ->columns('iSchoolId,sSchoolName')
                ->from('Admin\Models\school\XhschoolInfo')
                ->where('bDelete= 0 and ( iStatus = 1 or iStatus = 2 ) ');

            $schoolIds = School::getPower();
            if ($schoolIds !== true) {
                $builder->andWhere('iSchoolId in ({ids:array})', ['ids' => $schoolIds]);
            }
            if ($key) {
                $builder->andWhere('sSchoolName like :key:', ['key' => '%'.$key.'%']);
            }
            $data = Main::runBuilderPage($builder);
            return $this->sendJsonResponse($data);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }

    /**
     * 获取教师日志
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20181009
     */
    public function getTchLogAction()
    {
        try {
            $schoolId = $this->request->getPost('schoolId', 'int');
            $startTime = $this->request->getPost('startTime', 'string');
            $endTime   = $this->request->getPost('endTime', 'string');
            $key = $this->request->getPost('key', 'string');
            $state = $this->request->getPost('state', 'string');
            $iTTchId = $this->request->getPost('iTTchId', 'int');
            if (!$schoolId) {
                return $this->sendJsonResponse(['total'=> 0, 'rows' => []]);
            }
            $builder = $this->modelsManager->createBuilder()
                ->columns(['iTTchId','t.iUserId','tTrackTime','mContent','mPurpose','mResult','mAppUse',
                    'iState','mCheck','iTrackType','iSchoolId','t.iCreateUserId','u.sUserName as tchName'])
                ->from(['t' => 'Admin\Models\track\XhtrackTch'])
                ->leftJoin('Admin\Models\user\XhsysUser', 'u.iUserId = t.iUserId', 'u')
                ->where('t.bDelete = 0')
                ->orderBy('t.iCreateUserId,t.iUserId,t.tTrackTime desc');
            if (!$iTTchId) {
                if ($schoolId) {
                    $builder->andWhere('u.iSchoolId = :iSchoolId: ', ['iSchoolId' => $schoolId]);
                }
                if ($startTime && $endTime) {
                    $builder->andWhere(
                        't.tTrackTime >= :startTime: and t.tTrackTime <= :endTime:',
                        ['startTime' => $startTime, 'endTime' => $endTime]
                    );
                }
                if ($key) {
                    $builder->andWhere('u.sUserName like :key:', ['key' => '%'.$key.'%']);
                }
                if ($state) {
                    $builder->andWhere('iState = :iState:', ['iState' => $state]);
                }
            }
            if ($iTTchId) {
                $builder->andWhere('iTTchId = :iTTchId:', ['iTTchId' => $iTTchId]);
            }
            $data = Main::runBuilderPage($builder, self::$enums);
            foreach ($data['rows'] as &$row) {
                $row['tTrackTime'] = date('Y-m-d', strtotime($row['tTrackTime']));
                if ($row['iState'] == '待审核') {
                    $row['iState'] = '<div class="grid-cell-text-bg-gray">'.$row['iState'].'</div>';
                } else if ($row['iState'] == '审核通过') {
                    $row['iState'] = '<div class="grid-cell-text-bg-green">'.$row['iState'].'</div>';
                } else {
                    $row['iState'] = '<div class="grid-cell-text-bg-red">'.$row['iState'].'</div>';
                }
                $row['mContent'] = '<div title="'.$row['mContent'].'">'.$row['mContent'].'</div>';
                $row['mPurpose'] = '<div title="'.$row['mPurpose'].'">'.$row['mPurpose'].'</div>';
                $row['mResult'] = '<div title="'.$row['mResult'].'">'.$row['mResult'].'</div>';
                $row['mAppUse'] = '<div title="'.$row['mAppUse'].'">'.$row['mAppUse'].'</div>';
                $row['mCheck'] = '<div title="'.$row['mCheck'].'">'.$row['mCheck'].'</div>';

            }
            Main::runUserName($data['rows'], ['iCreateUserId' => 'sUserName'], false);
            return $this->sendJsonResponse($data);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }


    /**
     * 审核日志
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20181009
     */
    public function checkLogAction()
    {
        try {
            $ids   = $this->request->getPost('ids', 'int');
            $state = $this->request->getPost('state', 'int');
            $desc  = $this->request->getPost('desc', 'string');
//            $msgId = $this->request->getPost('msgId', 'int');
            if (!$ids) {
                return $this->sendErrorResponse(500, '缺少参数');
            }
            $objArr = XhtrackTch::find([
                'conditions' => 'bDelete = 0 and iTTchId in ({ids:array})',
                'bind'       => ['ids' => $ids]
            ]);
            $this->db->begin();
            $powerArr = Hrm::getInChargeUserIds();
            if ($powerArr === false) {
                return $this->sendErrorResponse(500, '没有审核权限');
            } else if ($powerArr === true) {
                foreach ($objArr as $obj) {
                    $obj->iState = $state;
                    $obj->mCheck = $desc;
                    if (!$obj->save()) {
                        throw new XhException('保存失败');
                    }
//                    Msg::setMsg('tch_log', [$obj->iTTchId]);
                }

            } else {
                $powerArr = array_values(array_filter(array_unique(array_column($powerArr, 'iUserId'))));
                foreach ($objArr as $obj) {
                    if (in_array($obj->iCreateUserId, $powerArr)) {
                        $obj->iState = $state;
                        $obj->mCheck = $desc;
                        if (!$obj->save()) {
                            throw new XhException('保存失败');
                        }
//                        Msg::setMsg('tch_log', [$obj->iTTchId]);
                    }
                }
            }
            $this->db->commit();
            return $this->sendSuccessResponse('审批成功');
        } catch (\Exception $e) {
            $this->db->rollback();
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }










}